package com.example.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.redis.RedisCache;
import com.example.model.acl.dtos.AclLoginDto;
import com.example.model.common.dtos.ResponseResult;
import com.example.model.user.dtos.LoginUser;
import com.example.user.mapper.AclUserMapper;
import com.example.model.acl.pojos.Acl_user;
import com.example.user.service.AclUserService;
import com.example.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Transactional
@Slf4j
public class AclUserServiceImpl extends ServiceImpl<AclUserMapper, Acl_user> implements AclUserService {

    @Autowired
    AclUserMapper aclUserMapper;

    @Autowired
    RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public ResponseResult login(AclLoginDto dto){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(dto.getName(),dto.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        if(Objects.isNull(authentication)){
            throw new RuntimeException("登录失败");
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if(loginUser.getAcl_user().getForbid() == 1){
            throw new RuntimeException("登录失败");
        }
        String id = loginUser.getAcl_user().getId();
        Integer iid = Integer.parseInt(id);
        String token = AppJwtUtil.getToken(iid.longValue());
        Map<String,Object> data = new HashMap<>();
        data.put("token",token);
        redisCache.setCacheObject("acl_login:"+id,loginUser);
        return ResponseResult.okResult(data);
    }

    @Override
    public ResponseResult logout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String id = loginUser.getAcl_user().getId();
        id = "acl_login:"+id;
        redisCache.deleteObject(id);
        return ResponseResult.okResult(200,"退出登录成功");
    }
}
